<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

define('IN_ADMIN_COMPONENT_CONTROLLER', 'true');

class CustomerReportComponent
{
	function CustomerReportComponent()
	{
	}

	function action(&$params, $action)
	{
		return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);
		$languageId = (int)$params['languageId'];
		$paginate = (boolean)$params['paginate'];
		$max_rows = (int)$params['max_rows'];
		$offset = (int)$params['offset'];

		$sqlQuery = 'select o.customers_name, o.customers_company, o.currency, o.currency_value, sum(ot.value) as total, os.orders_status_name ' .
		'from ' . TABLE_ORDERS . ' o, ' . TABLE_ORDERS_TOTAL . ' ot, ' . TABLE_ORDERS_STATUS . ' os ' .
		"where o.orders_id=ot.orders_id and ot.class='ot_total' and o.orders_status=os.orders_status_id and os.language_id = $languageId " .
		'group by o.customers_id, o.orders_status ' .
		'order by total DESC, o.orders_status';
		if ($paginate) {
			$sqlQuery .= ' limit ' . $offset . ', ' . $max_rows;
		}
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		$i = 0;
		while($row = mysql_fetch_array($dataReturned))
		{
			$value{$handle}{$i}{'name'}= $row['customers_name'];
			$value{$handle}{$i}{'company'}= $row['customers_company'];
			$value{$handle}{$i}{'status'}= $row['orders_status_name'];
			$value{$handle}{$i}{'currency_code'}= $row['currency'];
			$value{$handle}{$i}{'currency_value'}= (double)$row['currency_value'];
			$value{$handle}{$i}{'total'}= (double)$row['total'];
			$i++;
		}

		if ($paginate) {
			$sqlQuery = 'select count(o.customers_id) as cnt from ' . TABLE_ORDERS . ' o group by o.customers_id, o.orders_status';
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$cnt = 0;
			while($row = mysql_fetch_array($dataReturned))
			{
				//$cnt = $cnt + (int)$row['cnt'];
				$cnt++;
			}

			$value{$handle . 'MetaData'}{'max_rows'}= (int)$max_rows;
			$value{$handle . 'MetaData'}{'offset'}= $offset;
			$value{$handle . 'MetaData'}{'page_links_max'} = (int)MAX_DISPLAY_PAGE_LINKS;
			$value{$handle . 'MetaData'}{'rows'}= $i;
			$value{$handle . 'MetaData'}{'total_rows'}= $cnt;
		}

		return $value;
	}
}
?>
